import {
  Dimension,
  DimensionTarget,
  selectPmData,
  submitPm,
  temporarySavePm
} from '@/api/myPerformance'
import {PMContent, PMLayout, PMNav} from '@/components/others/layout'
import {SplitLine} from '@/components/splitLine'
import {CnBoldSpan, CnNormalP} from '@/components/text'
import {useRouteQuery} from '@/hooks/pageRedirect'
import useMyPm from '@/hooks/pm/myPm'
import useOwner from '@/hooks/pm/owner'
import useProgress from '@/hooks/pm/progress'
import useGroup from '@/hooks/pm/group'
import {useTableLoading} from '@/hooks/tableHook'
import {SetTargetPageQuery, toMyPerformance} from '@/libs/pageRedirect'
import TargetTableCard from '../setTarget/components/targetTableCard'
import {defineComponent, reactive, computed, onMounted} from 'vue'

export default defineComponent({
  name: 'setTarget',
  setup(props, ctx) {
    const {route, router, getQueryData} = useRouteQuery({
      queryKeys: ['pmId', 'progressId']
    })

    let pageQuery = getQueryData<SetTargetPageQuery>()
    if (!pageQuery) {
      router.back()
      return () => <div></div>
    }

    const {
      pmId: defaultPmId,
      groupId: defaultGroupId,
      progressId: defaultProgressId,
      userDDId: defaultUserDDId
    } = pageQuery

    const {startLoading, closeLoading, loading} = useTableLoading()

    const {getPmProgress, excludeUserBySelectAppointUser} = useProgress({
      pmId: defaultPmId
    })

    const {owner, udpateOwner} = useOwner()

    const {getPmByPmId, pm, setPm, checkTargetWeight} = useMyPm()

    const {getPmGroupById} = useGroup()

    let state = reactive<{
      /**维度tabs栏，当前维度的id */
      dimensTabsActiveKey: number

      /**当前绩效的内容 （维度） */
      pmDataList: MyPm.PmData[] | null
      pmGroupBaseInfo: Evaluation.EvalutaionData | undefined
      /**保存/暂存时 发送的维度数据 */
      dimensions: Dimension[]
    }>({
      dimensTabsActiveKey: -1,
      pmDataList: null,
      pmGroupBaseInfo: undefined,
      dimensions: []
    })

    /**所有指标权重 */
    const targetWeightCount = computed(
      () =>
        eval(
          state.dimensions
            .map(item =>
              item.pmTargetList
                .filter(item => item.makeProperty !== 'delete')
                .map(target => target.pmTargetWeight)
            )
            .flat(Infinity)
            .join('+')
        ) as number
    )

    /**所有维度权重 */
    const dimensionWeightCount = computed(
      () => eval((state.pmDataList || []).map(item => item.pmDimensionWeight).join('+')) as number
    )

    /**获取页面数据 */
    function getPageData() {
      startLoading()
      /**获取个人绩效中的维度 */
      selectPmData({pmId: Number(defaultPmId)})
        .then(pmdataListRes => {
          if (pmdataListRes.data) pmdataListRes.data.sort((a, b) => a.sort - b.sort)
          state.pmDataList = pmdataListRes.data || []
          console.log('个人绩效中有数据', pmdataListRes.data)
          state.dimensions = state.pmDataList.map<Dimension>(item => ({
            pmDimensionId: item.pmDimensionId,
            pmDimensionName: item.pmDimensionName,
            pmDimensionTypeCode: item.pmDimensionTypeCode,
            pmDimensionWeight: item.pmDimensionWeight,
            isCustomSelf: item.isCustomSelf,
            isImport: item.isImport,
            sort: item.sort,
            pmTargetList: item.pmTargetList.map<DimensionTarget>(target => ({
              isBonus: target.isBonus,
              pmTargetRange: target.pmTargetRange,
              pmTargetId: target.pmTargetId,
              appointScoreSign: target.appointScoreSign,
              appointUserDDId: target.appointUserDDId,
              makeProperty: undefined,
              pmTargetName: target.pmTargetName,
              pmTargetStand: target.pmTargetStand,
              pmTargetWeight: target.pmTargetWeight,
              sort: target.sort,
              isMustSelect: target.isMustSelect,
              pmDimensionId: target.pmDimensionId
            }))
          }))
          console.log(state.dimensions)
          state.dimensTabsActiveKey = state.pmDataList[0].sort

          closeLoading()
        })
        .catch(err => {
          closeLoading()
        })

      getPmByPmId({
        pmId: Number(defaultPmId),
        updatePm: true,
        success: data => {
          udpateOwner({ownerDDId: data.pmUserDDId})
        }
      })
    }

    function getPmGroupByIdCallBack(pmGroup: Evaluation.EvalutaionData) {
      pmGroup.pmGroupDimensionList.sort((a, b) => a.sort - b.sort)

      state.pmGroupBaseInfo = pmGroup

      console.log('个人绩效中没有指标数据，使用考评组中的默认指标', pmGroup, state.dimensions)

      closeLoading()
    }

    /**保存点击 */
    function handleSubmitClick() {
      if (!checkTargetWeight(state.dimensions)) return
      console.log(state.dimensions)
      startLoading()
      submitPm({pmProgressId: defaultProgressId, data: state.dimensions})
        .then(res => {
          closeLoading()
          router.back()
        })
        .catch(err => {
          closeLoading()
          getPageData()
        })
    }

    /**暂存点击 */
    function handleTemporarySaveClick() {
      startLoading()

      temporarySavePm({pmProgressId: defaultProgressId, data: state.dimensions})
        .then(res => {
          closeLoading()
          getPageData()
        })
        .catch(err => {
          closeLoading()
        })
    }

    onMounted(() => {
      getPmProgress({
        pmId: defaultPmId,
        updatePmProgress: true,
        success: data => {
          getPmGroupById({
            pmGroupId: Number(defaultGroupId),
            success: getPmGroupByIdCallBack
          })
          getPageData()
        }
      })
    })

    return () => (
      <PMLayout spinning={loading.value}>
        <PMNav
          backClick={() => {
            if (!pageQuery) return
            router.back()
          }}
        >
          <div class='h-full flex items-center'>
            {/* 考核表名称 */}
            <CnBoldSpan>{(pm.value?.pmUserName || '') + (pm.value?.pmFormName || '')}</CnBoldSpan>
            {/* 竖向分割线 */}
            <SplitLine class='h-1/2 w-2 ml-16 mr-32'></SplitLine>
            {/* 维度名称Tabs栏 */}
            {/* <a-tabs v-model={[state.dimensTabsActiveKey, 'activeKey']}>
              {state.pmDataList
                ? state.pmDataList.map(item => (
                    <a-tab-pane key={item.sort} tab={item.pmDimensionName}></a-tab-pane>
                  ))
                : null}
            </a-tabs> */}
            <span class='flex items-center gap-x-10'>
              <span class='bg-black rounded-4 overflow-hidden'>
                <img src={owner.value?.avatar || ''} class='w-36 h-36'></img>
              </span>
              <span>
                <CnNormalP>{owner.value?.userName || ''}</CnNormalP>
                <CnNormalP>{owner.value?.deptName || ''}</CnNormalP>
              </span>
            </span>
          </div>
        </PMNav>

        <PMContent class='pb-70'>
          <div class='flex flex-col gap-y-16'>
            {state.pmDataList
              ? state.pmDataList.map((item, idx) =>
                  owner.value ? (
                    <TargetTableCard
                      sourceType='self'
                      pmData={item}
                      hidden={false}
                      dimension={state.dimensions[idx]}
                      pmId={Number(defaultPmId)}
                      groupId={Number(defaultGroupId)}
                      onDimensionChange={data => {
                        state.dimensions[idx] = data
                      }}
                      owner={owner.value}
                      showAppointScore={
                        state.pmGroupBaseInfo?.appointScoreSwitch === 1 ? true : false
                      }
                      excludeUserIds={excludeUserBySelectAppointUser.value}
                    ></TargetTableCard>
                  ) : null
                )
              : null}
          </div>
        </PMContent>

        <div class='absolute bottom-0 left-0 w-full h-60 px-32 shadow-pageFooter bg-white z-10 flex items-center justify-end gap-x-32'>
          {/* <a-button onClick={handleTemporarySaveClick}>暂存</a-button> */}
          <a-button type='primary' onClick={handleSubmitClick}>
            提交并同意
          </a-button>
        </div>
      </PMLayout>
    )
  }
})
